package com.pub.tools;


/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 * <p>
 * The MailBean provides client access SMTP server for sending e-mail.
 * Because the bean use JavaMail library.It's usefully for sending e-mail.
 * And it Include query DB to get mail addresses for send mail to those address.
 * </p>
 * <p>
 * For example, A simple send mail example. <br>
 * &nbsp;  import java.util.*; <br>
 * &nbsp;  import javax.mail.*; <br>
 * &nbsp;  import javax.mail.event.*; <br>
 * &nbsp;  import javax.mail.internet.*; <br>
 * &nbsp;  import javax.activation.*; <br>
 * &nbsp;  import java.sql.*; <br>
 * &nbsp;  import com.alpha.bean.MailBean; <br>
 * &nbsp;  public class testMail { <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;  public static void main(String[] args) throws Exception { <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     String MFromAddr = ""; <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     String MToAddr   = ""; <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     String mSubject  = "Notice of WorkFlow!"; <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     String mailText  = ""; <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     Hashtable reclist = new Hashtable(); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     Hashtable replist = new Hashtable(); <br>
 *
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     MailBean jmail = new MailBean(); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     jmail.setMailServ("hqmail1.alphanetworks.com"); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     jmail.setSender("05413","tan_chen@alphanetworks.com"); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     reclist.put("05413","tan_chen@alphanetworks.com"); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     jmail.setReceivers(reclist); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     jmail.addAttachFile("C:\\autoexec.bat"); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     jmail.setBody("This is a testing mail."); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     jmail.sendMail(); <br>
 * &nbsp;&nbsp;&nbsp;&nbsp;        } <br>
 * &nbsp;&nbsp;  } <br>
 * </p>
 */

public class MailBean {
   private boolean blnDebug;

   public MailBean(boolean pblnDebug) {
       blnDebug=pblnDebug;
   }

   /**
    * The Construtor initialize mail server name;
    * @param mailServ. SMTP server host or server name
    */
   public MailBean(String mailServ,boolean pblnDebug) {
      MailServer = mailServ;
      blnDebug=pblnDebug;
   }

   //private PropertyBean  rb  = new PropertyBean("Mail");

   private String    MailServer = null;
   //rb.getString("mailServer");
   private String    Sender     = null;
   private String    SendAddr   = null;
   private Hashtable<String,String> RecvList   = null;
   private Hashtable<String,String> CcList     = null;
   private Hashtable<String,String> BccList    = null;
   private String    Replier    = null;
   private String    RepAddr    = null;
   private Hashtable<String,String> Repliers   = null;
   private String    Subject    = null;
   private String    MsgContent = null;
   private Vector<String>    FileName   = new Vector<String>();

   /**
    * Set Mail Server.
    * @param mailServ. The Domain Name of Mail Server.
    */
   public void   setMailServ(String mailServ){
      MailServer = mailServ;
   }

   /**
    * Get Domain Name of Mail Server.
    * return String. The Domain Name of Mail Server.
    */
   public String getMailServ(){ return MailServer; }

   /**
    * Set Mail Address of Sender.
    * @param sendAddr. The Mail Address of Mail Sender.
    */
   public void   setSender(String sendAddr) {
      Sender = sendAddr.substring(0, sendAddr.indexOf("@"));
      SendAddr = sendAddr;
   }

   /**
    * Set Mail Address of Sender.
    * @param sender. The Name of Mail Sender.
    * @param sendAddr. The Mail Address of Mail Sender.
    */
   public void   setSender(String sender,String sendAddr) {
      Sender = sender;
      SendAddr = sendAddr;
   }

   /**
    * Get Name of Sender.
    * return String. The Name of Mail Sender.
    */
   public String getSender()   { return Sender;   }

   /**
    * Get Mail Address of Sender.
    * return String. The Mail Address of Mail Sender.
    */
   public String getSendAddr() { return SendAddr; }

   /**
    * Set Mail Address List of Receiver.
    * @param recvlist. The Names and Mail Addresses of Mail Receiver.
    */
   public void   setReceivers(Hashtable<String,String> recvlist) {
      RecvList = recvlist;
   }

   /**
    * Set Mail Address List of Receiver.
    * @param recvlist. The Names and Mail Addresses of Mail Receiver.
    */
   public void   setReceivers(Vector<String> recvlist)    {
      RecvList = (Hashtable<String,String>)getMailAddr(recvlist);
   }

   /**
    * Set Mail Address List of Receiver.
    * @param recvlist. The Names and Mail Addresses of Mail Receiver.
    */
   public void   setReceivers(String recvlist)    {
      RecvList = new Hashtable<String,String>();
      RecvList.put(recvlist.substring(0,recvlist.indexOf('@')),recvlist);
   }

   /**
    * Get Mail Address List of Receiver.
    * return Hashtable. The Names and Mail Addresses of Mail Receiver.
    */
   public Hashtable<String,String> getReceivers() { return RecvList; }

   /**
    * Set Mail Address List of CCTo.
    * @param cctolist. The Names and Mail Addresses of Mail CCTo.
    */
   public void   setCcTo(Hashtable<String,String> cctolist) {
      CcList = cctolist;
   }

   /**
    * Set Mail Address List of CCTo.
    * @param cctolist. The Names and Mail Addresses of Mail CCTo.
    */
   public void   setCcTo(Vector<String> cctolist)    {
      CcList = (Hashtable<String,String>)getMailAddr(cctolist);
   }

   /**
   * Set Mail Address List of CCTo.
   * @param cclist. The Names and Mail Addresses of Mail CCTo.
   */
   public void   setCcTo(String cclist)    {
      //Vector ccvec = new Vector();
      //ccvec.add(cclist);
      //CcList = (Hashtable)getMailAddr(ccvec);
      CcList = new Hashtable<String,String>();
      CcList.put(cclist.substring(0,cclist.indexOf('@')),cclist);
   }

   /**
    * Get Mail Address List of CCTo.
    * return Hashtable. The Names and Mail Addresses of Mail CCTo.
    */
   public Hashtable<String,String> setCcTo() { return CcList; }

   /**
    * Set Mail Address List of BCCTo.
    * @param recvlist. The Names and Mail Addresses of Mail BCCTo.
    */
   public void   setBccTo(Hashtable<String,String> bcctolist) {
      BccList = bcctolist;
   }

   /**
    * Set Mail Address List of BCCTo.
    * @param bcctolist. The Names and Mail Addresses of Mail BCCTo.
    */
   public void   setBccTo(Vector<String> bcctolist)    {
      BccList = (Hashtable<String,String>)getMailAddr(bcctolist);
   }

   /**
   * Set Mail Address List of BCCTo.
   * @param bcclist. The Names and Mail Addresses of Mail BCCTo.
   */
   public void   setBccTo(String bcclist)    {
      //Vector bccvec = new Vector();
      //bccvec.add(bcclist);
      //BccList = (Hashtable)getMailAddr(bccvec);
      BccList = new Hashtable<String,String>();
      BccList.put(bcclist.substring(0,bcclist.indexOf('@')),bcclist);
   }

   /**
    * Get Mail Address List of BCCTo.
    * return Hashtable. The Names and Mail Addresses of Mail BCCTo.
    */
   public Hashtable<String,String> setBccTo() { return BccList; }

   /**
    * Set Mail Address List of Replier.
    * @param replier. The Names of Mail Replier.
    * @param repAddr. The Mail Addresses of Mail Replier.
    */
   public void   setReplier(String replier, String repAddr) {
      Replier = replier;
      RepAddr = repAddr;
      Repliers = null;
   }

   /**
    * Set Mail Address List of Replier.
    * @param repliers. The Names and Mail Addresses of Mail Replier.
    */
   public void   setReplier(Hashtable<String,String> repliers) {
      Replier = null;
      Repliers = repliers;
   }

   /**
    * Set Subject of Mail.
    * @param subject. The Subject of Mail.
    */
   public void   setSubject(String subject) {
      Subject = subject;
   }

   /**
    * Get Subject of Mail.
    * return String. The Subject of Mail.
    */
   public String getSubject() { return Subject; }

   /**
    * Set Content of Mail.
    * @param body. The Content of Mail.
    */
   public void   setBody(String body) {
      MsgContent = body;
   }

   /**
    * Get Content of Mail.
    * return String. The Content of Mail.
    */
   public String getBody() { return MsgContent; }

   /**
    * Add Attach File to Mail.
    * @param filename. The attached filename of Mail.
    */
   public void addAttachFile(String filename) {
      FileName.add(filename);
   }

   /**
    * Add Attach File to Mail.
    * @param filename. The attached filenames of Mail.
    */
   public void addAttachFile(Vector<String> filename) {
      FileName = filename;
   }

   /**
    * Delete Attach File to Mail.
    * @param filename. The attached filename of Mail.
    */
   public void delAttachFile(String filename) {
      FileName.remove(filename);
   }

   /**
    * 取得DB的Mail Address
    * @param userid
    * @return Object.
    */
   @SuppressWarnings("unchecked")
private Hashtable<String,String> getMailAddr(Object userid) { //Single: param-String, return-String ; Multi: param-Vector, return-Vector
    try {
      if ( userid == null ) return null;
      else {
           Hashtable<String,String> addrHsh = new Hashtable<String,String>();
        if ( userid instanceof String ) {
           addrHsh.put(userid.toString(),userid.toString());
           return addrHsh;
         } else if ( userid instanceof String[] ) {
            if (((String[])userid).length == 0) return null;
            for (int i=0; i < ((String[])userid).length; i++) {
             addrHsh.put(((String[])userid)[i].toString(),((String[])userid)[i].toString());
           }
           return addrHsh;
         } else if ( userid instanceof Vector ){
           if (((Vector<String>)userid).size() == 0) return null;
           for (int i=0; i < ((Vector)userid).size(); i++) {
             addrHsh.put(((Vector)userid).toString(),((Vector)userid).toString());
           }
           return addrHsh;
         } else if ( userid instanceof Hashtable ){
            if (((Hashtable)userid).size() == 0) return null;
            addrHsh = (Hashtable)userid;
            return addrHsh;
         } else return null;
      }
    } catch (Exception e) {
      System.out.println("MailBean.java (getMailAddr) --> Get Mail Address Exception:" + e.toString());
      return null;
    }
   }

   /**
    * Get Info of Mail Server and send mail to receivers.
    * @return boolean. If send mail success return true else false.
    */
   public boolean sendMail(){
     boolean retVal = false;

     if ( RecvList != null && RecvList.size() > 0 ) {
       InternetAddress[] recvAddrs  = new InternetAddress[RecvList.size()];
       InternetAddress[] ccAddrs    = null;
       InternetAddress[] bccAddrs   = null;


       InternetAddress[] replyAddrs = null;
       Properties props = new Properties();
       props.put("mail.smtp.host"         , MailServer );
       props.put("mail.host"              , MailServer );
       props.put("mail.transport.protocol", "smtp"     );
       props.put("mail.from"              , SendAddr   );
       Session session = Session.getInstance(props, null);
       try {
         MimeMessage msg = new MimeMessage(session);
         msg.setSubject(Subject,"Big5");                          //1.設定信件Title
         msg.setFrom( new InternetAddress(SendAddr, Sender) );    //2.設定寄件者位址
         Vector<String> keyVec = new Vector<String>(RecvList.keySet());           //3.取得收件人工號或名稱列表
         Vector<String> valVec = new Vector<String>(RecvList.values());           //  取得收件人E-Mail位址
         for ( int i=0; i < RecvList.size(); i++ ) {              //  設定收件人E-Mail Address
           recvAddrs[i] = new InternetAddress( (String)valVec.elementAt(i), (String)keyVec.elementAt(i) );
           if (blnDebug) System.out.println("MailBean.java (sendMail) --> Re-Key : "+(String)keyVec.elementAt(i));
           if (blnDebug) System.out.println("MailBean.java (sendMail) --> Re-Value : "+(String)valVec.elementAt(i));
         }

       if ( CcList != null && CcList.size() > 0 ) {
         ccAddrs    = new InternetAddress[CcList.size()];
         keyVec = new Vector<String>(CcList.keySet());
         valVec = new Vector<String>(CcList.values());
         for ( int i=0; i < CcList.size(); i++ ) {              //  設定收件人E-Mail Address
           ccAddrs[i] = new InternetAddress( (String)valVec.elementAt(i), (String)keyVec.elementAt(i) );
           if (blnDebug) System.out.println("MailBean.java (sendMail) --> Cc-Key : "+(String)keyVec.elementAt(i));
           if (blnDebug) System.out.println("MailBean.java (sendMail) --> Cc-Value : "+(String)valVec.elementAt(i));
         }
       }
       if ( BccList != null && BccList.size() > 0 ) {
          bccAddrs   = new InternetAddress[BccList.size()];
          keyVec = new Vector<String>(BccList.keySet());
          valVec = new Vector<String>(BccList.values());
          for ( int i=0; i < BccList.size(); i++ ) {              //  設定收件人E-Mail Address
            bccAddrs[i] = new InternetAddress( (String)valVec.elementAt(i), (String)keyVec.elementAt(i) );
            if (blnDebug) System.out.println("MailBean.java (sendMail) --> Bcc-Key : "+(String)keyVec.elementAt(i));
            if (blnDebug) System.out.println("MailBean.java (sendMail) --> Bcc-Value : "+(String)valVec.elementAt(i));
         }
       }

         //Message.RecipientType.TO,Message.RecipientType.CC,Message.RecipientType.BCC
         if (blnDebug) System.out.println("MailBean.java (sendMail) --> reciver:"+recvAddrs);
         msg.setRecipients(Message.RecipientType.TO, recvAddrs);  //4.設定信件的收件者
         msg.setRecipients(Message.RecipientType.CC, ccAddrs);
         msg.setRecipients(Message.RecipientType.BCC, bccAddrs);
         if ( Replier != null && Repliers == null ) {             //5.設定收件時，信件回應者的E-Mail Address
           replyAddrs = new InternetAddress[1];
           replyAddrs[0] = new InternetAddress(RepAddr, Replier);
         } else if ( Replier == null && Repliers != null ) {      //  ( 回應者為多人時 )
           replyAddrs = new InternetAddress[Repliers.size()];
           keyVec = new Vector<String>(Repliers.keySet());                //  取得回應者工號或名稱列表
           valVec = new Vector<String>(Repliers.values());                //  取得回應者E-Mail位址
           for ( int i=0; i < Repliers.size(); i++ ) {            //  設定回應者E-Mail Address
             replyAddrs[i] = new InternetAddress( (String)valVec.elementAt(i), (String)keyVec.elementAt(i) );
           }
         }
         if ( replyAddrs != null ) msg.setReplyTo(replyAddrs);
         msg.setSentDate(new java.util.Date());                   //6.設定送件日期
         //msg.setText(MsgContent);

         /* Added by Claire 20030812 */
         if (FileName.size() > 0) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(MsgContent,"text/html;charset=Big5");

            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);

            MimeBodyPart mbp2 = null;
            DataSource fds = null;

            for (int fileCount = 0 ; fileCount < FileName.size() ; fileCount++) {
               mbp2 = new MimeBodyPart();
               fds = new FileDataSource(FileName.get(fileCount).toString());
               mbp2.setDataHandler(new DataHandler(fds));
               mbp2.setFileName(fds.getName());

               mp.addBodyPart(mbp2);
            }

            msg.setContent(mp);
         } else {
            msg.setContent(MsgContent,"text/html;charset=Big5");     //7.設定信件顯示格式
         }

         //Transport trans = session.getTransport();
         //trans.send(msg);
         Transport.send(msg);                                     //8.傳送信件

         //Transport Event的種類：
         //MESSAGE_DELIVERED           -- 所有訊息都傳送成功,address in validSent[], validUnsent[]=null, invalid[]=null
         //MESSAGE_NOT_DELIVERED       -- 所有訊息都沒傳送成功,validSent[]=null, validUnsent[]=some, invalid[]=some
         //MESSAGE_PARTIALLY_DELIVERED -- 有些成功，有些失敗, validSent[]=some, validUnSent[]=some, invalid[]=some
         /*
         Transport trans = session.getTransport(mToAddr[0]);
         trans.addConnectionListener(this);
         trans.addTransportListener(this);
notifyTransportListeners(int type,Address[] validSent,Address[] validUnsent,Address[] invalid,Message msg)
         trans.connect();
         trans.sendMessage(msg);
         */
         if  ( TransportEvent.MESSAGE_DELIVERED ==1) {
            if (blnDebug) System.out.println("MailBean.java (sendMail) --> mail send");
            retVal = true;
         } else {
            if (blnDebug) System.out.println("MailBean.java (sendMail) --> mail did not send");
         }
       }catch (MessagingException me) {
         System.out.println("MailBean.java (sendMail) --> Send Mail Exception:  "  + me.toString());
       } catch (java.io.UnsupportedEncodingException ie) {
         System.out.println("MailBean.java (sendMail) --> Set Mail From Address Exception:" + ie.toString());
       }
     } else if (blnDebug) System.out.println("MailBean.java (sendMail) --> No Specified Receivers.");
     return retVal;
   } //End-sendMail
   /*
   public static void main(String[] args) throws Exception {
          String MFromAddr = "";
          String MToAddr   = "";
          String mSubject  = "Notice of WorkFlow!";
          String mailText  = "";
          Hashtable reclist = new Hashtable();
          Hashtable replist = new Hashtable();

          MailBean jmail = new MailBean();
          jmail.setMailServ("mailsrv1.dlink.com.tw");
          jmail.setSender("05377","claire_kuo@dlink.com.tw");
          reclist.put("05377","claire_kuo@dlink.com.tw");
          reclist.put("05331","claire_kuo@dlink.com.tw");
          jmail.setReceivers(reclist);
          jmail.addAttachFile("C:\\tmuninst.ini");
          jmail.addAttachFile("C:\\totalcmd\\TOTALCMD.INC");
          jmail.delAttachFile("C:\\tmuninst.ini");
          jmail.addAttachFile("C:\\totalcmd\\HISTORY.TXT");
          try {jmail.setSubject("Test...");} catch(Exception e) {}
          jmail.setBody("This is a testing mail.<BR>");
          jmail.sendMail();
      }
  */
}
